package com.weishenai.Mapper;

import com.weishenai.Builder.BaseRule;
import com.weishenai.Builder.UpdateRuleSqlBuilder;
import com.weishenai.Utils.CommonUtils;
import com.weishenai.Utils.ExecSqlUtils;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * @Auther: weishenai
 * @Date: 2021/09/30/18:43
 * @Description:
 */
public class UpdateMapper {
    /**
     * @Description: 更新
     * @Param: [o] 实体
     * @return: int
     * @Author: weishenai
     * @Date: 2021/10/1
     */
    public int update(Object o) {
        int affectRow = -1;
        UpdateRuleSqlBuilder updateRuleSqlBuilder = new UpdateRuleSqlBuilder();
        try {
            affectRow = ExecSqlUtils.updateInfo(updateRuleSqlBuilder.updateBuilder(o), updateRuleSqlBuilder.getValueArr());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return affectRow;
    }

    /**
     * @Description: 插入实体
     * @Param: [o]
     * @return: int
     * @Author: weishenai
     * @Date: 2021/10/1
     */
    public int insert(Object o) {
        int affectRow = -1;
        UpdateRuleSqlBuilder updateRuleSqlBuilder = new UpdateRuleSqlBuilder();
        try {
            affectRow = ExecSqlUtils.updateInfo(updateRuleSqlBuilder.insertBuilder(o), updateRuleSqlBuilder.getValueArr());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return affectRow;
    }

    /**
     * @Description: 删除实体
     * @Param: [o] 实体信息
     * @return: int
     * @Author: weishenai
     * @Date: 2021/10/1
     */
    public int delete(Object o) {
        BaseRule baseRule = BaseRule.getInstance();
        List<Map<String, Object>> deleteMap = CommonUtils.getFieldAndValues(o);
        for (Map map : deleteMap) {
            baseRule.andEqual((String) map.get("fieldName"), map.get("value"));
        }
        return delete(baseRule, o);
    }

    public int delete(BaseRule baseRule, Object o) {
        int affectRow = -1;
        UpdateRuleSqlBuilder updateRuleSqlBuilder = new UpdateRuleSqlBuilder(baseRule);
        try {
            affectRow = ExecSqlUtils.updateInfo(updateRuleSqlBuilder.deleteBuilder(o, true), updateRuleSqlBuilder.getValueArr());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return affectRow;
    }

    public int deleteById(String tableName, Object id) {
        int affectRow = -1;
        BaseRule baseRule = BaseRule.getInstance();
        baseRule.andEqual("id", id);
        UpdateRuleSqlBuilder updateRuleSqlBuilder = new UpdateRuleSqlBuilder(baseRule);
        try {
            affectRow = ExecSqlUtils.updateInfo(updateRuleSqlBuilder.deleteBuilder(tableName, false), updateRuleSqlBuilder.getValueArr());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return affectRow;
    }
}
